package com.suncloud.location.locationbysuncloud;

import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.test.AndroidTestCase;
import android.text.TextUtils;
import android.util.Log;

import java.util.ArrayList;

/**
 * Created by Administrator on 2017/6/28 0028.
 */

public class ContactsTest extends AndroidTestCase {
    private static final String TAG = "ContactsTest";


    /**
     * 获取手机上的电话簿
     * 1、先读取contacts表，获取ContactsID；
     * 2、再在raw_contacts表中根据ContactsID获取RawContactsID；
     * 3、然后就可以在data表中根据RawContactsID获取该联系人的各数据了。
     */
    public void testGetContacts() {
//        Uri uri = Uri.parse("content://com.android.contacts/contacts");//访问所有联系人
        Uri uri = ContactsContract.Contacts.CONTENT_URI;//这个更方便各个版本的Android系统
        ContentResolver contentResolver = getContext().getContentResolver();
        Cursor cursor = contentResolver.query(uri, null, null, null, null);
        while (cursor.moveToNext()) {
            String contact_id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            String contact_name = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
            StringBuilder stringBuilder = new StringBuilder("contactId =");
            stringBuilder.append(contact_id).append(",contact_name =").append(contact_name);
            Cursor phones = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?", new String[]{contact_id}, null);
            // 上面的ContactsContract.CommonDataKinds.Phone.CONTENT_URI
            // 可以用下面的phoneUri代替
            // Uri phoneUri=Uri.parse("content://com.android.contacts/data/phones");

            while (phones.moveToNext()) {
                String contact_phone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                stringBuilder.append(",contact_phone =" + contact_phone);
            }
            phones.close();
            Cursor emails = contentResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + "=?", new String[]{contact_id}, null);
            while (emails.moveToNext()) {
                String contact_email = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                stringBuilder.append(",emali = " + contact_email);
            }
            emails.close();
            Log.d("testGetContacts", stringBuilder.toString());
        }
        cursor.close();
    }

    /**
     * 单独添加一个联系人
     */
    public void testInsert() {
        ContentValues contentValues = new ContentValues();
        // 首先向RawContacts.CONTENT_URI执行一个空值插入，目的是获取系统返回的rawContactId
        Uri rawContact_uri = getContext().getContentResolver().insert(ContactsContract.RawContacts.CONTENT_URI, contentValues);
        long rawContactId = ContentUris.parseId(rawContact_uri);
        // 往data表入姓名数据
        contentValues.clear();
        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
        contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);// 内容类型
        contentValues.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, "我就是测试1");
        getContext().getContentResolver().insert(ContactsContract.Data.CONTENT_URI, contentValues);
        // 往data表入电话数据
        contentValues.clear();
        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
        contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);// 内容类型
        contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER, "88888888");
        contentValues.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
        getContext().getContentResolver().insert(ContactsContract.Data.CONTENT_URI, contentValues);
        // 往data表入Email数据
        contentValues.clear();
        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
        contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);// 内容类型
        contentValues.put(ContactsContract.CommonDataKinds.Email.DATA, "xxxx@QQ.con");
        contentValues.put(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK);
        getContext().getContentResolver().insert(ContactsContract.Data.CONTENT_URI, contentValues);
        //往data表中插入群组数据
        contentValues.clear();
        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
        contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE);// 内容类型
        contentValues.put(ContactsContract.CommonDataKinds.Organization.DATA, "sos号码");
        getContext().getContentResolver().insert(ContactsContract.Data.CONTENT_URI, contentValues);
    }

    /**
     * 批量添加联系人，效率高
     */
    public void testBatchInsert() throws RemoteException, OperationApplicationException {
        ArrayList<ContentProviderOperation> ops = new ArrayList<>();
        int rawContactInsertIndex = 0;
        for (int i = 1; i <= 10; i++) {
            rawContactInsertIndex = ops.size();
            ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
                    .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
                    .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
                    .withYieldAllowed(true).build());
            // 添加姓名
            ops.add(ContentProviderOperation
                    .newInsert(android.provider.ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(ContactsContract.RawContacts.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                    .withValue(ContactsContract.RawContacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, "测试" + i)
                    .withYieldAllowed(true).build());
            // 添加号码
            ops.add(ContentProviderOperation
                    .newInsert(android.provider.ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(ContactsContract.RawContacts.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                    .withValue(ContactsContract.RawContacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, "88888" + i)
                    .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
                    .withValue(ContactsContract.CommonDataKinds.Phone.LABEL, "").withYieldAllowed(true).build());
            // 添加邮箱
            ops.add(ContentProviderOperation
                    .newInsert(android.provider.ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(ContactsContract.RawContacts.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                    .withValue(ContactsContract.RawContacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.Email.DATA, "xxxx" + i + "@QQ.com")
                    .withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK)
                    .withYieldAllowed(true).build());
            // 添加群组
            ops.add(ContentProviderOperation
                    .newInsert(android.provider.ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(ContactsContract.RawContacts.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                    .withValue(ContactsContract.RawContacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.Organization.DATA, "情亲号码")
                    .withYieldAllowed(true).build());
        }
        if (ops != null) {
            // 真正添加
            ContentProviderResult[] results = mContext.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
            for (ContentProviderResult result : results) {
                Log.d("BatchAddContact==", result.uri.toString());
            }
        }
    }

    /**
     * 根据条件删除联系人
     * 非常简单只需要将raw_contacts表中指定RawContactID（其实在raw_contacts表中，应该就是_id列中的数据）的行删除，其他表中与之关联的数据都会自动删除。
     * Android帮助文档：When a raw contact is deleted, all of its Data rows as
     * well as StatusUpdates, AggregationExceptions, PhoneLookup rows are
     * deleted automatically.
     */
    public void testDel() {
        String name = "Hhhh";
        ContentResolver contentResolver = getContext().getContentResolver();
        //方法一
//        Cursor query = contentResolver.query(ContactsContract.RawContacts.CONTENT_URI, new String[]{ContactsContract.Data._ID}, ContactsContract.Data.DISPLAY_NAME + "=?", new String[]{name}, null);
//        while (query.moveToNext()) {
//            String id = query.getString(query.getColumnIndex(ContactsContract.Data._ID));
//            contentResolver.delete(ContactsContract.RawContacts.CONTENT_URI, ContactsContract.Data.DISPLAY_NAME + "=?", new String[]{name});
//            contentResolver.delete(android.provider.ContactsContract.Data.CONTENT_URI, ContactsContract.Contacts.Data.RAW_CONTACT_ID + "=?", new String[]{id});
//        }
//        query.close();

        //方法二
        //根据名字在Contacts表中，找出符合的行，并只需要_ID列
//        Cursor query = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, new String[]{ContactsContract.Data._ID}, ContactsContract.Data.DISPLAY_NAME + "=?", new String[]{name}, null);
//        //遍历每一行
//        while (query.moveToNext()) {
//            //得到此行中的_ID列的内容id
//            String id = query.getString(query.getColumnIndex(ContactsContract.Data._ID));
//            //拿着这个id，去RawContacts表中查找数据（注意的是，这个id在此表中对应的是CONTACT_ID列），得到CONTACT_ID列数据=id的结果；我们只需要此表中的_ID列
//            Cursor query1 = contentResolver.query(ContactsContract.RawContacts.CONTENT_URI, new String[]{ContactsContract.RawContacts.Data._ID}, ContactsContract.RawContacts.CONTACT_ID + "=?", new String[]{id}, null);
//            //再次遍历
//            while (query1.moveToNext()) {
//                //得到RawContacts表中的_ID列的数据id
//                String raw_contact_id = query1.getString(query1.getColumnIndex(ContactsContract.RawContacts.Data._ID));
//                //我们拿着这个id，去删除RawContacts表中对应的数据，就可以删掉所以数据了,两种删法如下：
////                contentResolver.delete(ContactsContract.RawContacts.CONTENT_URI, ContactsContract.RawContacts.Data._ID + "=?", new String[]{raw_contact_id});//方法1
//                contentResolver.delete(ContentUris.withAppendedId(ContactsContract.RawContacts.CONTENT_URI, Long.parseLong(raw_contact_id)), null, null);//方法2
//            }
//            query1.close();
//        }
//        query.close();

        //方法三
        Cursor query = contentResolver.query(ContactsContract.RawContacts.CONTENT_URI, new String[]{ContactsContract.RawContacts.Data._ID}, ContactsContract.Data.DISPLAY_NAME + "=?", new String[]{name}, null);
        while (query.moveToNext()) {
            //得到此行中的_ID列的内容id
            String id = query.getString(query.getColumnIndex(ContactsContract.RawContacts.Data._ID));
            //我们拿着这个id，去删除RawContacts表中对应的数据，就可以删掉所以数据了,两种删法如下：
//                contentResolver.delete(ContactsContract.RawContacts.CONTENT_URI, ContactsContract.RawContacts.Data._ID + "=?", new String[]{id});//方法1
            contentResolver.delete(ContentUris.withAppendedId(ContactsContract.RawContacts.CONTENT_URI, Long.parseLong(id)), null, null);//方法2
        }
        query.close();
    }

    /**
     * 更新联系人
     * 联系人的所有信息都是保存在data表中，所以要更新联系人，我们只需要根
     * 据RawContactID和MIMETYPE修改data表中的内容。
     */
    public void testUpdate() {
        //根据名字修改电话号码
        String name = "测试7";
        ContentValues contentValues = new ContentValues();
        contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER, "7777777");
        contentValues.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE);
        ContentResolver contentResolver = getContext().getContentResolver();
        Cursor cursor = contentResolver.query(ContactsContract.RawContacts.CONTENT_URI, new String[]{ContactsContract.RawContacts.Data._ID}, ContactsContract.Data.DISPLAY_NAME + "=?", new String[]{name}, null);
        while (cursor.moveToNext()) {
            String id = cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.Data._ID));
            contentResolver.update(ContactsContract.Data.CONTENT_URI, contentValues, ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[]{id, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE});
        }
        cursor.close();
    }

    /**
     * 删除所有联系人
     */
    public void testdeleteAllContacts() {
        ContentResolver contentResolver = getContext().getContentResolver();
        Cursor query = contentResolver.query(ContactsContract.RawContacts.CONTENT_URI, new String[]{ContactsContract.RawContacts.Data._ID}, null, null, null);
        while (query.moveToNext()) {
            //得到此行中的_ID列的内容id
            String id = query.getString(query.getColumnIndex(ContactsContract.RawContacts.Data._ID));
            //我们拿着这个id，去删除RawContacts表中对应的数据，就可以删掉所以数据了,两种删法如下：
//                contentResolver.delete(ContactsContract.RawContacts.CONTENT_URI, ContactsContract.RawContacts.Data._ID + "=?", new String[]{id});//方法1
            contentResolver.delete(ContentUris.withAppendedId(ContactsContract.RawContacts.CONTENT_URI, Long.parseLong(id)), null, null);//方法2
        }
        query.close();
    }

    /**
     * 根据条件删除联系人
     */
    public void testdeleteContactsByCondition(String condition) {
        ContentResolver contentResolver = getContext().getContentResolver();
        Cursor query = contentResolver.query(ContactsContract.Data.CONTENT_URI, new String[]{ContactsContract.Data.RAW_CONTACT_ID}, ContactsContract.Data.MIMETYPE + " = ? AND " + ContactsContract.Data.DATA1 + "= ?", new String[]{ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE, TextUtils.isEmpty(condition) ? "情亲号码" : condition}, null);
        while (query.moveToNext()) {
            String raw_contact_id = query.getString(query.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));
            Log.d(TAG, "testdeleteContactsByCondition: " + raw_contact_id);
            contentResolver.delete(ContactsContract.RawContacts.CONTENT_URI, ContactsContract.RawContacts._ID + "=?", new String[]{raw_contact_id});
        }
        query.close();
    }
}
